// String.prototype.parseUrl = function(){
// 	var result = this;
// 	var index = result.indexOf("?") + 1;
// 	var result = result.slice(index);
// 	var result = result.split("&");
// 	var obj = {}
// 	result.forEach(function(item){
// 		var arr = item.split("=");
// 		obj[arr[0]] = arr[1]
// 	})
// 	return obj;
// }

var express = require("express");
var expressStatic = require("express-static");
var server = express();
var url = require("url");
var mysql = require("mysql");
var port = 81;



//创建数据库连接
var sql = mysql.createConnection({
	host:"localhost",
	user:"root",
	password:"zhangmin136302",
	database:"school",
})
sql.connect();

server.get("/getdata",(request,response)=>{
	console.log("接收到前端路由："+"getdata");
	sql.query('select * from zg',(error,data)=>{
		if(error){
			console.log(error)
			response.end("error")
		}
		else{
			console.log("查询成功，接口：getData")
			response.end(JSON.stringify(data))
		}
	})
})


	server.get("/chaxun",(request,response)=>{
	var id =url.parse(request.url,true).query.id;
	sql.query(`select*from zg where id="${id}"`,(error,data)=>{
		if(error){
			response.end("error")
			console.log(error)
		}
		else{
			console.log("删除成功，接口：chaxun")
			response.end(JSON.stringify(data))
		}
	})
})


server.get("/tianjia",(request,response)=>{
	var id =url.parse(request.url,true).query.id;
	var name =url.parse(request.url,true).query.name;
	var sex =url.parse(request.url,true).query.sex;
	var age =url.parse(request.url,true).query.age;
	var gongzi =url.parse(request.url,true).query.gongzi;
	var dizhi =url.parse(request.url,true).query.dizhi;
	var tel =url.parse(request.url,true).query.tel;
	sql.query(`insert into zg values ("${id}","${name}","${sex}","${age}","${gongzi}","${dizhi}","${tel}")`,(error,data)=>{
		if(error){
			response.end("error")
			console.log(error)
		}
		else{
			console.log("添加成功，接口：tianjia")
			response.end("success")
		}
	})
})


server.get("/delete",(request,response)=>{
	var id =url.parse(request.url,true).query.id;
	sql.query(`delete from zg where id="${id}"`,(error,data)=>{
		if(error){
			response.end("error")
			console.log(error)
		}
		else{
			console.log("删除成功，接口：delete")
			response.end("success")
		}
	})
})

server.get("/gai",(request,response)=>{
	var newid =url.parse(request.url,true).query.id;
	var newvalue =url.parse(request.url,true).query.value;
	var newname =url.parse(request.url,true).query.name;
	sql.query(`update zg set ${newname}="${newvalue}" where id="${newid}"`,(error,data)=>{
		if(error){
			response.end("error")
			console.log(error)
		}
		else{
			console.log(newvalue,newname,newid,)
			console.log("修改成功，接口：gai")
			response.end("success")
		}
	})
})


server.use(express.static('static'));
server.listen(port);
console.log(`server is runing at ${port}`);
